package com.yy.wga.common.web.exception;

import com.yy.wga.common.core.constants.GlobalConstant;
import com.yy.wga.common.core.dto.Result;
import com.yy.wga.common.core.enmus.EResponseCode;
import com.yy.wga.common.core.exception.BusinessException;
import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 * scanBasePackages ="com.hrz" 一定在应用中添加扫描，只有扫描到才可以处理
 *
 * @author ludezh
 * @version 1.0.0
 * @date 2020/11/23 21:44
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @Value("${spring.profiles.active}")
    private String profiles;

    /**
     * 业务异常处理(指自定义的业务异常提示)
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<Result<?>> handleBusinessException(BusinessException e) {
        log.error("全局异常捕获：", e);
        Result result = new Result(EResponseCode.SYSTEM_BUSINESS_ERROR);
        result.setSuccess(false);
        if (e.getCode() != null && !e.getCode().isEmpty()) {
            result.setCode(e.getCode());
        }
        if (e.getDescription() != null && !e.getDescription().isEmpty()) {
            result.setMessage(e.getDescription());
        }
        if (profiles.equals(GlobalConstant.ENV_DEV) || profiles.equals(GlobalConstant.ENV_TEST)) {
            result.setMessage(e.getMessage());
        }
        //TODO 判断异常记录是否需要入库,保存数据库 / 异步邮件通知 方便开发人员及时定位解决问题
//        if (e.getIsRecord()) {
//
//        }
        // 业务异常默认使用200code码
        return this.handleExceptionInternal(e, result, HttpStatus.OK);
    }

    /**
     * 处理自定义验证注解异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ValidationException.class)
    public ResponseEntity<Result<?>> handleValidationException(ValidationException e) {
        log.error("全局异常捕获：", e);
        Result result = new Result(EResponseCode.SYSTEM_PARAM_ERROR);
        result.setSuccess(false);
        if (profiles.equals(GlobalConstant.ENV_DEV) || profiles.equals(GlobalConstant.ENV_TEST)) {
            result.setMessage(e.getMessage());
        }
        return this.handleException(e, result);
    }

    /**
     * 数据合法性校验异常处理,检验对象加上@Validated
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Result<?>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("全局异常捕获：", e);
        Result result = new Result(EResponseCode.SYSTEM_PARAM_ERROR);
        result.setSuccess(false);
        String msg = null;
        if (null != e.getBindingResult().getFieldError()) {
            msg = e.getBindingResult().getFieldError().getDefaultMessage();
        }
        if (msg == null || msg.isEmpty()) {
            if (null != e.getBindingResult().getGlobalError()) {
                msg = e.getBindingResult().getGlobalError().getDefaultMessage();
            }
        }
        if (profiles.equals(GlobalConstant.ENV_DEV) || profiles.equals(GlobalConstant.ENV_TEST)) {
            result.setMessage(e.getMessage());
        }
        result.setMessage(msg);
        return this.handleException(e, result);
    }

    /**
     * 数据校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ResponseEntity<Result<?>> handleBindException(BindException e) {
        log.error("数据校验异常", e);
        Result result = Result.fail(EResponseCode.SYSTEM_PARAM_ERROR);
        org.springframework.validation.BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        assert fieldError != null;
        String msg = fieldError.getDefaultMessage();
        result.setMessage(msg);
        if (profiles.equals(GlobalConstant.ENV_DEV) || profiles.equals(GlobalConstant.ENV_TEST)) {
            result.setMessage(e.getMessage());
        }
        return this.handleException(e, result);
    }

    /**
     * 请求方法不存在/不可用异常处理(一般指请求方式不对,如get post)
     *
     * @param e
     * @return
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class, HttpMediaTypeNotSupportedException.class})
    public ResponseEntity<Result<?>> handleHttpRequestMethodNotSupportedException(Exception e) {
        log.error("请求方法异常：", e);
        Result result = null;
        if (e instanceof HttpRequestMethodNotSupportedException) {
            result = new Result(EResponseCode.SYSTEM_METHOD_NOT_ALLOWED);
        } else {
            result = new Result(EResponseCode.SYSTEM_REQUEST_FAILE);
        }
        if (profiles.equals(GlobalConstant.ENV_DEV) || profiles.equals(GlobalConstant.ENV_TEST)) {
            result.setMessage(e.getMessage());
        }
        result.setSuccess(false);
        return this.handleException(e, result);
    }

    /**
     * 系统异常处理，比如：404,500
     *
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<Result<?>> defaultErrorHandler(Exception e) {
        log.error("全局异常捕获：", e);
        Result result = Result.fail(EResponseCode.SYSTEM_BUSY_ERROR);
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            result = Result.fail(EResponseCode.ILLEGAL_REQUEST);
        }
        if (profiles.equals(GlobalConstant.ENV_DEV) || profiles.equals(GlobalConstant.ENV_TEST)) {
            result.setMessage(e.getMessage());
        }
        return this.handleException(e, result);
    }

    /**
     * 异常类的统一处理
     *
     * @param ex
     * @return org.springframework.http.ResponseEntity<com.hrj.domain.Result < ?>>
     * @author ludezh
     * @date 2020/11/23 22:04
     * @version 1.0.0
     */
    protected ResponseEntity<Result<?>> handleException(Exception ex) {
        Result<?> result = Result.fail();
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        return this.handleExceptionInternal(ex, result, status);
    }

    /**
     * 异常类的统一处理
     *
     * @param ex
     * @return org.springframework.http.ResponseEntity<com.hrj.domain.Result < ?>>
     * @author ludezh
     * @date 2020/11/23 22:04
     * @version 1.0.0
     */
    protected ResponseEntity<Result<?>> handleException(Exception ex, Result result) {
        HttpStatus status = HttpStatus.OK;
        return this.handleExceptionInternal(ex, result, status);
    }

    /**
     * 异常类的统一处理
     *
     * @param ex
     * @return org.springframework.http.ResponseEntity<com.hrj.domain.Result < ?>>
     * @author ludezh
     * @date 2020/11/23 22:04
     * @version 1.0.0
     */
    protected ResponseEntity<Result<?>> handleExceptionInternal(Exception ex, Result<?> result, HttpStatus status) {
        return new ResponseEntity<Result<?>>(result, status);
    }

}

